export const base64ToFile = (urlData, name) => {
  console.log(urlData)
  let arr = urlData.split(',')
  let mime = arr[0].match(/:(.*?);/)[1]
  let bstr = atob(arr[1])
  let n = bstr.length
  let u8arr = new Uint8Array(n)

  while(n--){
    u8arr[n] = bstr.charCodeAt(n);
  }
  let newFile = new File([u8arr], name, {type:mime});
  newFile.src = urlData;
  return newFile
}


export const arrToBase64 = (buffer) => {
  var binary = '';
  var bytes = new Uint8Array(buffer);
  for (var len = bytes.byteLength, i = 0; i < len; i++) {
    binary += String.fromCharCode(bytes[i]);
  }
  return window.btoa(binary);
}

export const convertFileSize = (fileByte) => {
  let fileSizeByte = fileByte;
  let fileSizeMsg = "";
  if (fileSizeByte < 1048576) fileSizeMsg = (fileSizeByte / 1024).toFixed(2) + "K";
  else if (fileSizeByte === 1048576) fileSizeMsg = "1MB";
  else if (fileSizeByte > 1048576 && fileSizeByte < 1073741824) fileSizeMsg = (fileSizeByte / (1024 * 1024)).toFixed(2) + "M";
  else if (fileSizeByte > 1048576 && fileSizeByte === 1073741824) fileSizeMsg = "1GB";
  else if (fileSizeByte > 1073741824 && fileSizeByte < 1099511627776) fileSizeMsg = (fileSizeByte / (1024 * 1024 * 1024)).toFixed(2) + "G";
  else fileSizeMsg = "文件超过1TB";
  return fileSizeMsg;
}


export const sleep = (millisecond) => {
  for (let t = Date.now();Date.now() - t <= millisecond;);
}

export const getNowTime = () => {
  const now = new Date()
  let y = now.getFullYear()
  let m = formatNum(now.getMonth()+1)
  let d =  formatNum(now.getDate())
  let h =  formatNum(now.getHours())
  let min =  formatNum(now.getMinutes())
  let s =  formatNum(now.getSeconds())
  return ''+y+m+d+h+min+s
}

export const getNowDate = () => {
  const now = new Date()
  let y = now.getFullYear()
  let m = formatNum(now.getMonth()+1)
  let d =  formatNum(now.getDate())
  return ''+y+'-'+m+'-'+d
}

const formatNum = (num) => {
  if (num < 10) {
    return '0' + num
  }
  return num
}
